package ilves;

/**
 *
 * @author Viljo Lehtinen
 */

import java.io.*;
import java.net.*;

public class UrlReader {

    private Course[] courses = new Course[200]; //Raja heitetty hatusta.

    public UrlReader () throws IOException {

        URL jsonUrl = new URL("http://www.cs.helsinki.fi/u/tkairi/rajapinta/courses.json");
        BufferedReader in = new BufferedReader(new InputStreamReader(jsonUrl.openStream()));

        String inputLine = "", course_name = "", start_day = "", end_day = "";
        int index = 0;

        while ((inputLine = in.readLine()) != null) {

            inputLine = decodeInput(inputLine);



            /* Let`s get the String`s needed to create an instance of a course.*/

            if (inputLine.substring(0, 1).equals("c")) {
                course_name = inputLine.substring(8, inputLine.length()-2);
            }
            if (inputLine.substring(0, 1).equals("s")) {
                start_day = inputLine.substring(12, 22);
            }
            if (inputLine.substring(0, 1).equals("e")) {
                end_day = inputLine.substring(10, 20);
                courses[index] = new Course( start_day, end_day,course_name);
                index++;
            }
        }

        in.close();
  }

    /* This method decodes the inputLines we get from the site:
     http://www.cs.helsinki.fi/u/tkairi/rajapinta/courses.json.*/
    private static String decodeInput(String s) {

       /* Let´s delete or change certain characters. */
       s = s.replaceAll("u00e4","ä");
       s = s.replaceAll("u00f6","ö");
       s = s.replaceAll("u00c4","Ä");
       s = s.replace("\"","");
       s = s.replace("\\","");

       /* This delete`s empty spaces at the beginning of the string*/
       for (int i = 0; i < s.length(); i++) {

           if (s.substring(i, i+1).equals(" ")) {
               s = s.substring(i+1, s.length());
           }
           else break;
       }

       return s;
    }
    public Course[] luodutKurssit() {
     return this.courses;
    }
    
    private static String[] parse(String s) {
       s = s.replaceAll("u00e4","ä");
       s = s.replaceAll("u00f6","ö");
       s = s.replaceAll("u00c4","Ä");
       s = s.replaceAll("\\\"", "'");

       // Katkaistaan kaksoispisteen kohdalta ja valitaan teksti uloimpien lainausmerkkien sisältä.
       String[] result = s.split(":");
       for (int i = 0; i < result.length; i++) {
           result[i] = result[i].substring(result[i].indexOf("\"")+1, result[i].lastIndexOf("\""));
           result[i] = result[i].trim();
       }

        return result;
    }

}
